<template>
  <div
    v-loading="loading"
    element-loading-text="加载中..."
    style="position: relative; display: flex; flex-direction: column; height: 100%"
  >
    <div class="top">
      <div class="nav">
        <el-tabs class="demo-tabs" v-model="activeName" @tab-change="tabClick">
          <el-tab-pane :name="0">
            <template #label>
              <span>
                全部工单（{{
                  OrderStatusQtyData?.finishOrderQty * 1 + OrderStatusQtyData?.cancelOrderQty * 1 ||
                  0
                }}）
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane :name="4">
            <template #label>
              <span class="custom-tabs-label">
                <span>已完成（{{ OrderStatusQtyData?.finishOrderQty || 0 }}）</span>
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane :name="5">
            <template #label>
              <span class="custom-tabs-label">
                <span>已取消（{{ OrderStatusQtyData?.cancelOrderQty || 0 }}）</span>
              </span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="app-container" style="display: flex; flex-direction: column; height: 100%">
      <div class="app-container-inner" style="display: flex; flex-direction: column">
        <div class="search flex-align-center">
          <!-- 日期类型 -->
          <el-select
            class="input-item mr5"
            v-model="dateType"
            placeholder="日期类型"
            @change="getOrderListData()"
          >
            <el-option
              v-for="item in dateTypeSele"
              :key="item.val"
              :value="item.val"
              :label="item.name"
            />
          </el-select>

          <!-- 选择时间 -->
          <el-select
            v-if="dateType"
            class="input-item mr5"
            v-model="radio1"
            placeholder="选择时间"
            clearable
            @change="radio1 == 1 ? '' : getOrderListData()"
          >
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :value="item.value"
              :label="item.title"
            />
          </el-select>

          <!-- 时间范围 -->
          <div class="select-time mr5" v-if="radio1 == 1">
            <DateRange ref="dateRangeRef" @change="handleDateChange" />
          </div>

          <!-- 工单单号 -->
          <el-input
            clearable
            v-model="input1"
            placeholder="工单单号"
            class="input-item mr5"
            @keyup.enter="getOrderListData"
            @clear="getOrderListData"
          />

          <!-- 客户名称/手机号/地址 -->
          <el-input
            clearable
            v-model="input2"
            @keyup.enter="getOrderListData"
            placeholder="客户名称/手机号/地址"
            class="input-item mr5"
            style="width: 200px"
            @clear="getOrderListData"
          />

          <div class="search_btn_group">
            <!-- 按钮组 -->
            <el-button type="primary" color="#007cff" class="search_btn" @click="getOrderListData">
              <el-icon class="mr5">
                <Search />
              </el-icon>
              搜索
            </el-button>
            <el-button class="reset_btn" @click="clearValue">
              <el-icon class="mr5">
                <RefreshRight />
              </el-icon>
              重置
            </el-button>
          </div>
        </div>
        <div class="table-list" style="flex: 1; position: relative">
          <el-table
            ref="tableList"
            height="100%"
            style="position: absolute"
            :border="true"
            stripe
            resizable
            :data="tableDataList"
            @row-dblclick="goDetail"
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <!-- 序号 -->
            <el-table-column type="index" label="序号" fixed="left" min-width="50" />
            <template v-for="item in OrderListTable" :key="item.name">
              <el-table-column
                show-overflow-tooltip
                :fixed="item.freezeColumn"
                :align="item.code == 'totalPrice' ? 'right' : 'left'"
                :prop="item.code"
                :label="item.name"
                v-if="item.showColumn"
                :width="tableColumnWidth[item.code] || '100'"
              >
                <template #default="scope">
                  <!--  -->
                  <template v-if="item.code == 'code'">
                    <span v-if="scope.row.isRepeatOrder" class="repeat">重</span>
                    <span v-if="scope.row.remindersStatus" class="reminder">催</span>
                    <span class="number" @click="goDetail(scope.row)">{{ scope.row.code }}</span>
                  </template>

                  <!-- 工单类型 -->
                  <template v-if="item.code == 'module'">
                    <span>{{ scope.row.module }}</span>
                  </template>

                  <!-- 工单状态 -->
                  <template v-if="item.code == 'status'">
                    <HStatus type="warning" v-if="scope.row.status === 1">待派单</HStatus>
                    <HStatus type="warning" v-if="scope.row.status === 2">待服务商确认</HStatus>
                    <HStatus type="warning" v-if="scope.row.status === 3">处理中</HStatus>
                    <HStatus type="success" v-if="scope.row.status === 4">已完成</HStatus>
                    <HStatus type="info" v-if="scope.row.status === 5">已取消</HStatus>
                  </template>

                  <!-- 客户地址 -->
                  <template v-if="item.code == 'userAddress'">
                    <span>{{
                      scope.row.province +
                      ' ' +
                      scope.row.city +
                      ' ' +
                      scope.row.area +
                      ' ' +
                      scope.row.town +
                      ' ' +
                      scope.row.address
                    }}</span>
                  </template>

                  <!-- 等级 -->
                  <template v-if="item.code == 'level'">
                    <span :style="{ color: scope.row.workLevelColor }">{{
                      scope.row.workLevel
                    }}</span>
                  </template>

                  <!-- 工单总费用 -->
                  <template v-if="item.code == 'totalPrice'">
                    <div style="text-align: left">￥{{ scope.row.totalPrice.toFixed(2) }}</div>
                  </template>

                  <!--  服务时长 -->
                  <template v-if="item.code == 'totalServiceTime'">
                    <span :style="{ color: scope.row.serviceTimeColor }">{{
                      scope.row.serviceTime
                    }}</span>
                  </template>

                  <!--工单来源  -->
                  <template v-if="item.code == 'source'">
                    <!-- //1-客服建单，2-400电话，3-扫码报单，4-ERP平台，5-电商平台，6-小程序报单，7-APP报单，8-第三方系统报单 -->
                    <span v-for="item in sources" :key="item.value">
                      <span v-if="scope.row.source === item.value">{{ item.title }}</span>
                    </span>
                    <!-- 第三方系统报单 -->
                  </template>

                  <!--商家结算总价-->
                  <template v-if="item.code === 'factorySettlementTotalPrice'">
                    <span v-if="scope.row.factorySettlementTotalPrice">
                      ￥{{ scope.row.factorySettlementTotalPrice }}
                    </span>
                  </template>

                  <!--服务商结算总价-->
                  <template v-if="item.code === 'networkSettlementTotalPrice'">
                    <span v-if="scope.row.networkSettlementTotalPrice">
                      ￥{{ scope.row.networkSettlementTotalPrice }}
                    </span>
                  </template>
                </template>

                <template #header>
                  <!-- 工单总费用 -->
                  <template v-if="item.code === 'totalPrice'">
                    <div style="display: flex; justify-content: flex-start">
                      {{ item.name }}
                    </div>
                  </template>
                </template>
              </el-table-column>
            </template>

            <!-- 自定义字段 -->
            <el-table-column
              show-overflow-tooltip
              v-for="(key, index) in arrList"
              :key="index"
              :label="key.name"
              :width="100"
            >
              <template #header>
                <div
                  ref="customFieldHeaderRef"
                  style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
                  :id="`custom-field-${index}`"
                  >{{ key.name }}</div
                >
              </template>
              <template #default="scope">
                <template v-for="i in scope.row.fieldVals" :key="i.id">
                  <div
                    ref="customFieldContentRef"
                    style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
                    :id="`custom-field-${index}`"
                  >
                    {{ i.id == key.id ? i.val : '' }}
                  </div>
                </template>
              </template>
            </el-table-column>

            <!-- 表单设置 -->
            <el-table-column align="center" fixed="right" width="38">
              <template #header>
                <el-tooltip effect="dark" content="列表设置" placement="top-start">
                  <!-- <el-icon @click="tableShowSet">
                      <Tools />
                    </el-icon> -->
                  <el-image
                    @click="tableShowSet"
                    style="display: flex; align-items: center; justify-content: center; width: 16px"
                    :src="setSvg"
                    :size="20"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="pagination"
            :list_total="totalList"
            @size-change="getOrderListData"
            @current-change="getOrderListData"
          />
        </div>
        <!-- <AssignDialog :assignAny="assignAny" :assignDialog="assignDialog" :selecttion="selecttion"
            @assign-dialog="assignDialog = false, isbatch = true" :isbatch="isbatch"
            @update-list="getOrderListData(), selecttion = [], arr = []">
          </AssignDialog> -->
        <!-- 工单导出弹窗 -->
        <!-- 列表设置 -->
        <TableVisibleDialog
          @update-list="getOrderListData(), getOrderListTableFieldList()"
          :type="2"
          :dialogTableVisible="dialogTableVisible"
          @set-table-dialog="dialogTableVisible = $event"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import type { TabsPaneContext } from 'element-plus'
  import { Search, RefreshRight } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import Pagination from '../../../components/Pagination/index.vue'
  import { getOrderListTableTitleField, getOrderListTableField } from '../../../api/order'
  import { getOrderArchivedList, getOrderArchivedStatusQty } from '../../../api/archived'
  import TableVisibleDialog from '../../../components/TableVisibleDialog.vue'
  import * as _ from 'lodash'
  import setSvg from '@/assets/order/set.svg'
  import DateRange from '@/components/DateRange.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.order.archiveList,
  })

  const tableDataList: any = ref(null) // 工单列表数据
  const OrderStatusQtyData: any = ref(null) // 工单状态数量数据

  const activeName = ref(0)
  const router = useRouter()
  const route = useRoute()
  const loading: any = ref(false)

  const pagination = ref()
  const totalList = ref(0) //列表总数量
  const dateType = ref(1)
  const dateTypeSele = ref([
    { name: '报单日期', val: 1 },
    { name: '归档日期', val: 2 },
  ])
  let arrList: any = ref([]) //自定义字段

  // 表格每一列的宽度
  const tableColumnWidth = {
    code: '140', // 工单编号
    createTime: '128', // 报单时间
    factory: '100', // 商家名称
    factorySettlementTotalPrice: '100', // 商家结算总价
    networkSettlementTotalPrice: '120', // 服务商结算总价
    status: '100', // 工单状态
    module: '170', // 工单类型
    userName: '90', // 客户姓名
    userPhone: '104', // 客户手机号
    userAddress: '200', // 客户地址
    orderGoods: '200', // 报单商品
    network: '120', // 服务商
    engineer: '80', // 工程师
    reservationDate: '128', // 预约时间
    serviceTime: '100', // 节点时效
    emp: '90', // 客服
    totalPrice: '90', // 工单总费用
    source: '80', // 工单来源
  }

  // 搜索栏
  const input1 = ref('') // 工单编号
  const input2 = ref('') // 搜索客户名称/手机号/地址
  const input4 = ref('') // 搜索商品品牌/名称/型号
  const tableList = ref() // 表格Dom

  // 表头搜索
  const value2 = ref('') // 申请时间
  const startTime = ref('') // 开始日期
  const endTime = ref('') // 结束日期
  // 筛选 1-报单时间 3-服务商 4-服务时长
  const radio1 = ref(4)
  const radio4 = ref(null)

  // 报单时间
  const timeOptions: any = ref([
    { title: '时间区间', value: 1 },
    { title: '今天', value: 2 },
    { title: '本周', value: 3 },
    { title: '本月', value: 4 },
    { title: '过去三个月', value: 5 },
  ])

  // 工单来源
  const sources: any = ref([
    { title: '客服建单', value: 1 },
    { title: '400电话', value: 2 },
    { title: '扫码报单', value: 3 },
    { title: 'ERP平台', value: 4 },
    { title: '电商平台', value: 5 },
    { title: '小程序报单', value: 6 },
    { title: 'APP报单', value: 7 },
    { title: '第三方系统报单', value: 8 },
  ])

  // 导航切换
  const tabClick = (tab: TabsPaneContext) => {
    activeName.value = Number(tab)
    getOrderListData()
  }

  // DateRange组件实例
  const dateRangeRef = ref<InstanceType<typeof DateRange> | null>(null)

  // 重置
  const clearValue = () => {
    if (dateRangeRef.value) {
      dateRangeRef.value.resetDateRange()
      isStartDateGreaterThanEndDate.value = false
    }
    dateType.value = 2
    radio1.value = 4
    input1.value = ''
    input2.value = ''
    input4.value = ''
    value2.value = ''
    startTime.value = null
    endTime.value = null
    radio4.value = null
    getOrderListData()
  }
  // 查看工单详细
  const goDetail = (val: any) => {
    router.push('/order/odetail/' + val.id + '?isArchive=true')
  }

  // 开始日期是否大于结束日期
  const isStartDateGreaterThanEndDate = ref(false)

  //获取工单归档列表
  const getOrderListData = _.debounce(async () => {
    if (isStartDateGreaterThanEndDate.value) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
      })
      return
    }
    let itmeType: any = null
    if (radio1.value) {
      // 筛选条件 时间类型
      itmeType = radio1.value
    }
    let tab: any = null
    if (activeName.value === 0) {
      //判断是切换为全部工单
      tab = null
    } else {
      tab = activeName.value
    }

    let data: any = {
      dateType: dateType.value, //报单时间类型
      dateValType: itmeType, //日期参数类型：1-时间区间，2-今天，3-本周，4-本月，5-过去三个月
      limit: pagination.value.size, //每页显示数量
      orderEndTime: endTime.value, //报单/归档结束时间
      workNo: input1.value, //工单单号
      orderStartTime: startTime.value, //报单/归档开始时间
      page: pagination.value.current, //当面页码
      status: tab, //4-已完成，5-已取消
      userKeyword: input2.value, // 客户关键词：客户名称/手机号/地址
    }
    loading.value = true
    await getOrderArchivedList(data).then((res) => {
      if (res.data.success) {
        tableDataList.value = res.data.data.rows
        totalList.value = Number(res.data.data.total)
        getOrderStatusQtyData()
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 4000,
            offset: 200,
          })
      }
      loading.value = false
    })
  }, 0)
  // 获取工单归档列表状态数量
  const getOrderStatusQtyData = async () => {
    await getOrderArchivedStatusQty().then((res) => {
      if (res.data.success) {
        OrderStatusQtyData.value = res.data.data.row
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 4000,
            offset: 200,
          })
      }
    })
  }

  // 获取工单列表表头的工单自定义字段
  const getOrderListTableTitleFieldList = async () => {
    const res = await getOrderListTableTitleField()
    if (res.data.success) {
      arrList.value = res.data.data.rows
    }
  }

  // 获取工单列表表头字段
  const dialogTableVisible = ref(false)
  const OrderListTable: any = ref(null)
  const getOrderListTableFieldList = () => {
    getOrderListTableField(2).then((res) => {
      if (res) {
        OrderListTable.value = res.data.data.rows
      }
    })
  }
  // 点击列表设置
  const tableShowSet = () => {
    dialogTableVisible.value = true
  }

  // 日期更新事件
  const handleDateChange = (param: {
    startDate: string
    endDate: string
    isStartDateGreaterThanEndDate: boolean
  }) => {
    startTime.value = param.startDate
    endTime.value = param.endDate
    isStartDateGreaterThanEndDate.value = param.isStartDateGreaterThanEndDate
    if (param.isStartDateGreaterThanEndDate) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
      })
    }
  }

  watch(
    () => route.name,
    (value) => {
      if (value === 'archived') {
        getOrderListData()
        getOrderListTableTitleFieldList()
        getOrderListTableFieldList()
      }
    },
  )

  onMounted(() => {
    new Promise(() => {
      getOrderListData()
      getOrderListTableTitleFieldList()
      getOrderListTableFieldList()
    })
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
